import 'package:flutter/material.dart';
import 'package:httpdio/screens/posts_screen.dart';
import 'package:provider/provider.dart';
import '../models/comment_model.dart';
import '../models/user_model.dart';
import '../service/comment_service.dart';
import '../service/user_service.dart';
import '../widgets/error_widget.dart';

class CommentsScreen extends StatefulWidget{
  final int? postId;// 可选的帖子ID，用于筛选特定帖子的评论
  final String? postTitle;//帖子标题（用于标题）
  final int? userId; // 新增：支持按用户ID筛选
  final String? userName; // 新增：用户名称

  const CommentsScreen({super.key,this.postId,this.postTitle,  this.userId,
    this.userName});

  @override
  _CommentsScreenState createState()=>_CommentsScreenState();

}
class _CommentsScreenState extends State<CommentsScreen>{
  late Future<List<Comment>> _futureComments;
  final ScrollController _scrollController = ScrollController();
  int _page = 1;
  final int _limit = 20;
  bool _isLoadingMore = false;
  bool _hasMore = true;
  User? _commentUser ;//存储评论用户信息

  @override
  void initState() {
    super.initState();
    _futureComments = _loadComments();
    _scrollController.addListener(_scrollListener);
    // 如果提供了用户ID，加载用户信息
    if (widget.userId != null) {
      _loadUserInfo();
    }
  }
  Future<void> _loadUserInfo() async {
    try {
      final user = await context.read<UserService>().getUser(widget.userId!);
      setState(() => _commentUser = user);
    } catch (e) {
      // 处理错误，但不要阻止评论加载
      print('加载用户信息失败: $e');
    }
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  Future<List<Comment>> _loadComments({bool loadMore = false}) async{
    if(loadMore){
      setState(()=>_isLoadingMore = true);
      _page++;
    }else{
      _page = 1;
    }

    try{
      final commentService = context.read<CommentService>();
      final comments ;

      if (widget.postId != null) {
        // 按帖子加载评论
        comments = await commentService.getCommentsForPostPaginated(
          widget.postId!,
          _page,
          _limit,
        );
      } else if (widget.userId != null) {
        // 按用户加载评论
        comments = await commentService.getCommentsByUserPaginated(
          widget.userId!,
          _page,
          _limit,
        );
      } else {
        // 加载所有评论
        comments = await commentService.getCommentsPaginated(
          _page,
          _limit,
        );
      }
      setState(()=>_hasMore = comments.length ==_limit);
      return comments;
    }catch(e){
      throw e;
    }finally{
      if (loadMore) {
        setState(() => _isLoadingMore = false);
      }
    }
  }

  void _scrollListener(){
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      if (_hasMore && !_isLoadingMore) {
        _loadComments(loadMore: true);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.postId !=null
      ?'${widget.postTitle}的评论':'所有评论'),
      actions: [
        IconButton(onPressed: ()=>setState(() =>
          _futureComments = _loadComments()),
         icon: const Icon(Icons.refresh))
      ],
      ),
      body: FutureBuilder<List<Comment>>(
        future: _futureComments,
        builder: (context,snapshot){
          if (snapshot.connectionState == ConnectionState.waiting &&
              !snapshot.hasData) {
            return const Center(child: CircularProgressIndicator());
          }
          if (snapshot.hasError) {
            return CustomErrorWidget(
              message: snapshot.error.toString(),
              onRetry: () => setState(() => _futureComments = _loadComments()),
            );
          }
          final comments = snapshot.data ?? [];
          if (comments.isEmpty) {
            return _buildEmptyState();
          }
          return RefreshIndicator(
              onRefresh: ()async{
                setState(() =>
                _futureComments = _loadComments()
                );},

          child: ListView.builder(
            controller: _scrollController,
            itemCount: comments.length+(_isLoadingMore?1:0),
            itemBuilder: (context,index){
              if(index>=comments.length){
                return _buildLoadMoreIndicator();
              }
              final comment = comments[index];
              return _buildCommentItem(comment);
            },
          ),

          );

          },

      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add_comment),
        onPressed: () => _createNewComment(context),
      ),
    );
  }

  Widget _buildCommentItem(Comment comment) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                CircleAvatar(
                  backgroundColor: Colors.blue[100],
                  child: Text(comment.name.isNotEmpty ? comment.name[0] : '?'),
                ),
                const SizedBox(width: 10),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(comment.name, style: const TextStyle(fontWeight: FontWeight.bold)),
                      Text(comment.email, style: const TextStyle(fontSize: 12, color: Colors.grey)),
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            Text(comment.body),
            const SizedBox(height: 8),
            if (comment.postId != null) ...[
              const Divider(),
              Text(
                '关联帖子: ${comment.postId}',
                style: const TextStyle(color: Colors.blue, fontSize: 12),
              ),
            ],
          ],
        ),
      ),
    );
  }
  Widget _buildTitle() {
    if (widget.postId != null) {
      return Text(widget.postTitle != null
          ? '${widget.postTitle}的评论'
          : '帖子评论');
    } else if (widget.userId != null) {
      return Text(widget.userName != null
          ? '${widget.userName}的评论'
          : '用户评论');
    }
    return const Text('所有评论');
  }
  Widget _buildUserHeader() {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.blue[50],
        border: Border(bottom: BorderSide(color: Colors.grey[300]!)),
      ),
      child: Row(
        children: [
          CircleAvatar(
            radius: 24,
            backgroundImage: NetworkImage(_commentUser?.avatarUrl ?? ''),
            child: _commentUser?.avatarUrl == null
                ? const Icon(Icons.person)
                : null,
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  _commentUser?.displayName ?? '未知用户',
                  style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
                ),
                if (_commentUser?.email != null)
                  Text(
                    _commentUser!.email,
                    style: const TextStyle(fontSize: 14, color: Colors.grey),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }
  Widget _buildCommentList() {
    return FutureBuilder<List<Comment>>(
      future: _futureComments,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting &&
            !snapshot.hasData) {
          return const Center(child: CircularProgressIndicator());
        }

        if (snapshot.hasError) {
          return CustomErrorWidget(
            message: snapshot.error.toString(),
            onRetry: () => setState(() => _futureComments = _loadComments()),
          );
        }

        final comments = snapshot.data ?? [];

        if (comments.isEmpty) {
          return _buildEmptyState();
        }

        return RefreshIndicator(
          onRefresh: () async {
            setState(() => _futureComments = _loadComments());
          },
          child: ListView.builder(
            controller: _scrollController,
            itemCount: comments.length + (_isLoadingMore ? 1 : 0),
            itemBuilder: (context, index) {
              if (index >= comments.length) {
                return _buildLoadMoreIndicator();
              }

              final comment = comments[index];
              return _buildCommentItem(comment);
            },
          ),
        );
      },
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(Icons.comment, size: 64, color: Colors.grey),
          const SizedBox(height: 16),
          Text(
            widget.postId != null ? '该帖子还没有评论' : '暂无评论',
            style: const TextStyle(fontSize: 18),
          ),
          const SizedBox(height: 8),
          ElevatedButton(
            child: const Text('添加评论'),
            onPressed: () => _createNewComment(context),
          ),
        ],
      ),
    );
  }

  Widget _buildLoadMoreIndicator() {
    return const Padding(
      padding: EdgeInsets.symmetric(vertical: 16),
      child: Center(child: CircularProgressIndicator()),
    );
  }

  void _createNewComment(BuildContext context) {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('添加新评论功能待实现')),
    );
  }

  void _navigateToPost(BuildContext context, int postId) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => PostsScreen(postId: postId),
      ),
    );
  }
}